(in-package :gwee)

(defclass radio-button (widget callback-mixin data-mixin foreground-mixin background-mixin)
  ((selected :initform nil :initarg :selected :accessor selected)
   (radio-id :initarg :radio-id :accessor radio-id))
  (:default-initargs
   :width :minimum :height :minimum))

(defmethod synchronize-height-minimum ((view radio-button) (parent view) width height)
    (max (sdl:get-font-height :font (view-font view))
         20))

(defmethod synchronize-width-minimum ((view radio-button) (parent view) width height)
  (let* ((data (format-data view)))
    (+ 23 (if data
              (sdl:get-font-size data
                                 :size :w
                                 :font (view-font view))
              0))))

(defun radio-buttons-with-id (id &optional (top *top-view*))
  (let (acc)
    (labels ((walk (view)
               (when (and (typep view 'radio-button)
                          (eql (radio-id view) id))
                 (push view acc))
               ;; Only walk through visible subviews so that radio
               ;; buttons in other switchable-layout children with the
               ;; same ID aren't touched.
               (mapc #'walk (view-visible-subviews view))))
      (walk top)
      acc)))

(defmethod mouse-press-event ((view radio-button) button x y)
  (declare (ignore button x y ))
  (unless (disabled-p view)
    (let ((radios (delete view (radio-buttons-with-id (radio-id view))))
          (selected (selected view)))
      (dolist (r radios)
        (when (selected r)
          (setf (selected r) nil
                (view-needs-update-p r) t)))
      (setf (selected view) t
            (view-needs-update-p view) t)
      (unless (or selected
                  (null (click-callback view)))
        (funcall (click-callback view) view)))))

(defmethod draw-view ((view radio-button))
  (let ((size (1- (min (view-width view)
                       (view-height view))))
        (data (format-data view)))
    (draw-rectangle view 0 (u:half (- (view-height view) size))
                    size size)
    (when data
      (draw-text view data (+ size 3) (u:half (- (view-height view)
                                                 (sdl:get-font-height :font (view-font view))))))
    (when (selected view)
      (draw-line view 4 4
                 (- size 4)
                 (- size 4))
      (draw-line view
                 (- size 4) 4
                 4 (- size 4)))))
